package Blob;

import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.IOException;

import javax.media.MediaLocator;
import javax.swing.JFrame;

import BlobUI.*;

public class Main extends JFrame {

	BlobPublishingCamera camera;
	BlobPublishingCameraPanel cameraPanel;

	public Main(String videoPath) {
		camera = new BlobPublishingCamera();

		if (!VideoValidationChecker(videoPath)) {// check Media Locator build
			System.out.println("Could not open video entity: " + videoPath);
		}

		cameraPanel = new BlobPublishingCameraPanel(camera);
		setContentPane(cameraPanel);
		setSize(1000, 600);
		setTitle("CS3246_Demo: Moving Objects Tracker");
		setVisible(true);
	}

	void start() {
		addWindowListener(new WindowAdapter() {
			@Override
			public void windowClosing(WindowEvent e) {
				camera.close();
				System.exit(0);
			}
		});
		cameraPanel.switchFeed(0);
	}

	private boolean VideoValidationChecker(String path) {
		MediaLocator ml;
		String url = "file:" + path;
		if ((ml = new MediaLocator(url)) == null) {
			System.err.println("Cannot build media locator from: " + url);
			System.exit(0);
		}

		return camera.open(ml);
	}

	private boolean autoOpen() {
		boolean success = false;
		int camNum = 0;
		String mediaLoc;
		do {
			mediaLoc = "vfw://" + camNum;
			System.out.println("Trying video for windows, camera #" + camNum
					+ ": " + mediaLoc);
			success = VideoValidationChecker(mediaLoc);
		} while (!success && (++camNum) < 4);
		return success;
	}

	/**
	 * Main program
	 */
	public static void main(String[] args) {
		String dirpath = "";
		try {
			dirpath = new java.io.File(".").getCanonicalPath();
			System.out.println(dirpath);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		String path = dirpath + "/example.avi";
		System.out.println(path);
		// path="G:\\motiondetection\\example.avi";
		Main frame = new Main(path);
		frame.start();
	}
}
